<template>
  <view class="uv-page" style="background-color: #fff;">
    <view class="uv-demo-block">
      <view class="uv-demo-block__content">
        <uv-form :model="form" :rules="rules" ref="form1" labelWidth="auto">
          <view v-if="form.taskIds.length>0">
            <uv-text align="center" type="info" :text="`已选择${form.taskIds.length}条任务进行批量下发`"></uv-text>
          </view>

          <uv-form-item prop="taskName" required label="任务名:" borderBottom v-if="!ids">
            <uv-input v-model="form.taskName" border="none" placeholder="请输入任务名"></uv-input>
          </uv-form-item>
          <uv-form-item prop="areaName" label="区域:" borderBottom @click="showAreaSelect" v-if="!ids">
            <uv-input v-model="form.areaName" disabled disabledColor="#ffffff" placeholder="请选择区域"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-form-item prop="announcements" label="注意事项:" v-if="!ids">
            <uv-textarea v-model="form.announcements" count placeholder="请输入注意事项"></uv-textarea>
          </uv-form-item>
          <uv-form-item prop="sampleGraph" label="示例图:" v-if="!ids">
            <view style="display: flex;align-items: flex-start;">
              <uv-upload :fileList="fileList1" name="1" multiple :maxCount="10" @afterRead="afterRead"
                         @delete="deletePic" width="80" height="80"></uv-upload>
            </view>
          </uv-form-item>
          <uv-form-item prop="remark" label="备注:" v-if="ids">
            <uv-textarea v-model="form.remark" count placeholder="请输入备注"></uv-textarea>
          </uv-form-item>
          <uv-form-item prop="timeType" label="类型:" borderBottom @click="showTypeTimeSelect" v-if="!ids">
            <uv-input v-model="timeTypeLabel" disabled disabledColor="#ffffff" placeholder="请选择类型"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>

          <uv-form-item prop="inspectorName" required label="检查人:" borderBottom @click="showInspectorSelect">
            <uv-input v-model="form.inspectorName" disabled disabledColor="#ffffff" placeholder="请选择检查人"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>

          <uv-form-item prop="inspectDeadline" required label="检查截止:" borderBottom @click="inspectDeadlineOpen">
            <uv-input v-model="form.inspectDeadline" disabled disabledColor="#ffffff" placeholder="请选择检查截止日期"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-radio-group @change="changeInspectDeadline">
            <uv-radio
                shape="square"
                :customStyle="{margin: '8px'}"
                v-for="(item, index) in commonTime"
                :key="index"
                :label="item"
                :name="item">
            </uv-radio>
          </uv-radio-group>
          <uv-form-item prop="userName" label="执行人:" borderBottom @click="showUserSelect">
            <uv-input v-model="form.userName" disabled disabledColor="#ffffff" placeholder="请选择执行人"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>

          <uv-form-item prop="deadline" required label="执行截止:" borderBottom @click="deadlineOpen">
            <uv-input v-model="form.deadline" disabled disabledColor="#ffffff" placeholder="请选择执行截止日期"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-radio-group @change="changeTimeType">
            <uv-radio
                shape="square"
                :customStyle="{margin: '8px'}"
                v-for="(item, index) in commonTime"
                :key="index"
                :label="item"
                :name="item">
            </uv-radio>
          </uv-radio-group>
        </uv-form>

        <uv-button type="primary" :text="`${form.taskIds.length>0 ? '批量下发': '下发'}`" customStyle="margin-top: 10px"
                   @click="submit"></uv-button>

        <!-- 选择执行人 -->
        <uv-picker ref="userSelectPicker"
                   :columns="userData"
                   @confirm="userSelect"
                   @cancel="userCancel"
                   keyName="realName"></uv-picker>

        <!-- 选择检查人 -->
        <uv-picker ref="inspectorSelectPicker"
                   :columns="userData"
                   @confirm="inspectorSelect"
                   @cancel="inspectorCancel"
                   keyName="realName"></uv-picker>

        <!-- 选择截止日期 -->
        <uv-datetime-picker :minDate="minDate" ref="deadlinePicker" v-model="deadlineDate"
                            mode="datetime"
                            :formatter="formatter"
                            @confirm="deadlineConfirm"
                            @cancel="deadlineCancel"></uv-datetime-picker>

        <!-- 选择任务类型 -->
        <uv-picker ref="typeTimeSelectPicker"
                   :columns="typeData"
                   @confirm="typeTimerSelect"
                   @cancel="typeTimeCancel"
                   keyName="dictValue"></uv-picker>

        <!-- 选择区域 -->
        <uv-picker ref="areaSelect"
                   :columns="areas"
                   @confirm="areaSelect"
                   keyName="title"
                   @cancel="areaCancel"></uv-picker>

        <!-- 选择检查截止日期 -->
        <uv-datetime-picker :minDate="minDate" ref="inspectDeadlinePicker" v-model="inspectDeadlineDate"
                            mode="datetime"
                            :formatter="formatter"
                            @confirm="inspectDeadlineConfirm"
                            @cancel="inspectDeadlineCancel"></uv-datetime-picker>

      </view>
    </view>
  </view>
</template>

<script>

import TaskAPI from '@/api/task'
import CommonAPI from '@/api/common'
import UploadAPI from "@/api/upload";
import {formatHmTime, formatTime, parseTime} from "@/utils/media";
import DictAPI from "@/api/dict";
import AreaAPI from "@/api/area";

export default {
  data() {
    return {
      commonTime: ['11:00','11:30',  '14:00', '17:30','18:00', '21:00', '23:59'],
      lastTime: '',
      sampleGraph: [],
      userData: [], // 待选用户列表
      typeData: [],
      areas: [], // 区域列表
      timeTypeLabel: '',
      deadlineDate: new Date().getTime(),
      inspectDeadlineDate: new Date().getTime(),
      minDate: new Date().getTime(),
      form: {
        taskIds: [],
        userId: '',
        userName: '',
        areaName: '',
        inspectorName: '', // 检查人
        deadline: '', // 截止日期
        taskName: '', //任务标题
        timeType: '', //
        announcements: '',
        sampleGraph: '', // 任务图示例
        inspectDeadline: '', // 检查截止时间
      },
      fileList1: [], // 上传的作业图
      rules: {
        taskName: {
          required: true,
          message: '请输入任务名',
          trigger: ['blur']
        },
        userName: {
          required: false,
          message: '请输入执行人',
          trigger: ['blur']
        },
        deadline: {
          required: true,
          message: '请选择截止日期',
          trigger: ['blur']
        },
        inspectorName: {
          required: true,
          message: '请输入检查人',
          trigger: ['blur']
        }
      },
      ids: '',
    };
  },
  onShow() {
    this.init()
  },
  onLoad(e) {
    this.ids = e.ids
    if (e.ids) {
      this.form.taskIds = e.ids.split(',')
    }
  },
  onReady() {
    this.$refs.deadlinePicker.setFormatter(this.formatter)
    // 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
    this.$refs.form1.setRules(this.rules)
  },
  methods: {
    changeTimeType(e) {
      console.info(e)
      this.form.deadline = formatHmTime(e)
    },
    changeInspectDeadline(e){
      this.form.inspectDeadline = formatHmTime(e)
    },
    init() {
      CommonAPI.userAttendance().then(res => {
        if (res.code !== 200) {
          return
        }
        this.userData = [[...res.data]]
      })

      DictAPI.dictByCodeList(
          DictAPI.dictByCodeList({
            code: 'task_time_type'
          }).then(res => {
            this.typeData = [[...res.data]]
          }))

      AreaAPI.tree(1).then(res => {
        if (res.code !== 200) {
          return
        }
        this.areas = [
          [...res.data]
        ]
      })
    },

    // 区域选择
    showAreaSelect() {
      this.$refs.areaSelect.open();
    },
    areaSelect(e) {
      // 正确获取选中项
      const element = e.value[0] // 单列选择器取第一个元素
      this.form.areaId = element.id
      this.form.areaName = element.title
    },
    areaCancel(e){
      this.form.areaId = ''
      this.form.areaName = ''
    },

    // 任务类型选择
    showTypeTimeSelect() {
      this.$refs.typeTimeSelectPicker.open();
    },
    typeTimerSelect(e) {
      this.timeTypeLabel = e.value[0].dictValue
      this.form.timeType = e.value[0].dictKey
    },
    typeTimeCancel() {
      this.form.timeType = ''
      this.timeTypeLabel = ''
    },

    // 执行人选择
    showUserSelect() {
      this.$refs.userSelectPicker.open();
    },
    userSelect(e) {
      // 正确获取选中项
      const element = e.value[0] // 单列选择器取第一个元素
      this.form.userId = element.id
      this.form.userName = element.realName
    },
    userCancel(){
      this.form.userId = ''
      this.form.userName = ''
    },

    // 检查人选择
    showInspectorSelect() {
      this.$refs.inspectorSelectPicker.open();
    },
    inspectorSelect(e) {
      // 正确获取选中项
      const element = e.value[0] // 单列选择器取第一个元素
      this.form.inspectorId = element.id
      this.form.inspectorName = element.realName
    },
    inspectorCancel() {
      this.form.inspectorId = ''
      this.form.inspectorName = ''
    },

    // 检查截止日期选择
    inspectDeadlineOpen() {
      this.inspectDeadlineDate = this.form.inspectDeadline
      this.$refs.inspectDeadlinePicker.open();
    },
    inspectDeadlineConfirm(e) {
      console.info(e)
      this.form.inspectDeadline = formatTime(e.value)
      this.inspectDeadlineDate = formatTime(e.value)
    },
    inspectDeadlineCancel() {
      this.inspectDeadlineDate = new Date().getTime()
      this.form.inspectDeadline = ''
    },

    // 截止日期选择
    deadlineOpen() {
      this.deadlineDate = this.form.deadline
      this.$refs.deadlinePicker.open();
    },
    deadlineConfirm(e) {
      this.form.deadline = formatTime(e.value)
      this.deadlineDate = formatTime(e.value)
    },
    deadlineCancel() {
      this.deadlineDate = new Date().getTime()
      this.form.deadline = ''
    },

    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      }
      if (type === 'month') {
        return `${value}月`
      }
      if (type === 'day') {
        return `${value}日`
      }
      if (type === 'hour') {
        return `${value}时`
      }
      if (type === 'minute') {
        return `${value}分`
      }
      return value
    },

    // 提交
    submit() {
      console.info(JSON.stringify(this.form))
      if (this.fileList1.length > 0) {
        this.form.sampleGraph = this.fileList1.map(i => i.url).join(',')
      }
      // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
      this.$refs.form1.validate().then(res => {
        //  检查截止日期是否小于当前时间
        if (parseTime(this.form.deadline) < new Date().getTime()) {
          uni.showToast({
            icon: 'none',
            title: '截止日期小于当前时间'
          })
          return
        }

        if (this.form.taskIds.length > 0) {
          TaskAPI.taskBatchAssign(this.form).then(res => {
            if (res.code === 200) {
              uni.showToast({
                icon: 'success',
                title: '提交成功'
              })
            }
            uni.reLaunch({
              url: '/pages/usertask/usertask'
            })
          })
        } else {
          TaskAPI.addTask(this.form).then(res => {
            if (res.code === 200) {
              uni.showToast({
                icon: 'success',
                title: '提交成功'
              })
            }else{
              uni.showToast({
                icon: 'none',
                title: res.msg
              })
              return
            }
            uni.reLaunch({
              url: '/subpackage/task/task'
            })
          })
        }

      }).catch(errors => {
        uni.showToast({
          icon: 'error',
          title: '校验失败'
        })
      })
    },

    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1)
    },
    // 新增图片
    async afterRead(event) {
      console.info(event)
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url)
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url: result
        }))
        fileListLen++
      }
    },
    async uploadFilePromise(url) {
      let data = await UploadAPI.uploadFile(url)
      return data.link
    }
  }
}
</script>

<style lang="scss" scoped>
.uv-page {
  padding: 15px 15px 40px 15px;
}

.uv-demo-block {
  margin-bottom: 22px;
}

.uv-demo-block__title {
  font-size: 14px;
  color: #8f9ca2;
  margin-bottom: 8px;
}

.uv-demo-block__title {
  font-size: 14px;
  color: #8f9ca2;
  margin-bottom: 8px;
}

.uv-demo-block__content {
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
}

.uv-content {
  padding: 24rpx;
}
</style>